package dao;

import model.Farm;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;

public class FarmDateBase {
    private String dbdriver="com.mysql.jdbc.Driver";
    private String dburl="jdbc:mysql://localhost:3306/sctu-javaweb-2018?serverTimezone=UTC&characterEncoding=UTF-8";
    private String dbuser="root";
    private String dbpassword="123456";
    private String username;

    public void setUsername(String username) {
        this.username = username;
    }
    public List<Farm> getfarmList()throws Exception{
        List<Farm> farmList=new ArrayList<Farm>();
        Connection connection=null;
        PreparedStatement preparedStatement=null;
        ResultSet resultSet=null;

        Class.forName(dbdriver);
        connection= DriverManager.getConnection(dburl,dbuser,dbpassword);

        String sql="select * from farm WHERE username=?";
        preparedStatement.setString(1,username);
        preparedStatement=connection.prepareStatement(sql);
        resultSet=preparedStatement.executeQuery();

        while (resultSet.next()){
            Farm farm=new Farm();
            farm.setId(resultSet.getInt(1));
            farm.setUsername(resultSet.getString(2));
            farm.setArea(resultSet.getString(3));
            farm.setPrice(resultSet.getFloat(4));
            farm.setBreed(resultSet.getString(5));
            farm.setEggs(resultSet.getInt(6));
            farm.setAlreadBreed(resultSet.getString(7));
            farm.setFarmImg(resultSet.getString(8));
            farmList.add(farm);
        }


        return farmList;
    }
}
